<template>
  <div class="container" :class="{ active: isChangeAvatar }">
    <div class="left" v-show="isChangeAvatar">
      <div class="choose-avatar">
        <i class="iconfont icon-dagou" @click="submit"></i>
        <div class="images">
          <div class="image" v-for="(img, index) in avatars" :key="index"
            :class="{ active: currentChooseAvatar === index }" @click="ImageUrl = ''; currentChooseAvatar = index">
            <img :src="useImageUrl(img)">
          </div>
          <!-- 图片上传 -->
          <div class="up-loader">
            <label for="file-upload" class="custom-file-upload">
              <i class="iconfont icon-tianjia"></i>
            </label>
            <input id="file-upload" type="file" @change="handleFileUpload">
          </div>
        </div>
      </div>
    </div>
    <div class="right">
      <div class="header">
        <img v-if="ImageUrl" :src="ImageUrl" @click="isChangeAvatar = !isChangeAvatar">
        <img v-else :src="useImageUrl(avatars[currentChooseAvatar])" @click="isChangeAvatar = !isChangeAvatar">
        <span class="iconfont icon-guanbi"
          @click="currentChooseAvatar = -1; ImageUrl = ''; $emit('closeUserInfo'); isChangeAvatar = false"></span>
      </div>
      <div class="main">
        <input type="text" :value="userStore.user.username" v-if="isEdit" @blur="handleChangeUsername" ref="inputRef">
        <span class="username" v-else>{{ userStore.user.username }}</span>
        <span class="iconfont icon-bianji" @click="isEdit = true" v-show="!isEdit"></span>
        <p class="error">{{ errorText }}</p>
      </div>
      <div class="footer">
        <el-button text bg class="logout" @click="handleLogout">退出登录</el-button>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, watch, nextTick } from 'vue'
import { useUserStore } from '../store/user'
import 'element-plus/es/components/message/style/css'
import { ElMessage } from 'element-plus'

const avatars = [
  'touxiang-01.svg', 'touxiang-02.svg', 'touxiang-03.svg', 'touxiang-04.svg', 'touxiang-05.svg', 'touxiang-06.svg', 'touxiang-07.svg', 'touxiang-08.svg', 'touxiang-09.svg', 'touxiang-10.svg', 'touxiang-11.svg', 'touxiang-12.svg'
]

export default defineComponent({
  emits: ['closeUserInfo'],
  setup(props, { emit }) {
    const isEdit = ref(false)

    const userStore = useUserStore()

    const inputRef = ref<HTMLInputElement>()
    watch(isEdit, async (newValue) => {
      if (newValue) {
        await nextTick()
        inputRef.value!.focus()
      }
    })
    const errorText = ref('')

    const handleChangeUsername = async (event: Event) => {
      // 如果新用户名不等于老用户名，则发送请求修改用户名
      let oldUsername = userStore.user.username
      let newUsername = (event.target! as HTMLInputElement).value
      if (!newUsername.trim()) {
        errorText.value = '用户名不能为空'
        inputRef.value!.focus()
        return
      }
      if (oldUsername !== newUsername) {
        let userInfo = {
          oldUsername,
          newUsername
        }
        const result = await userStore.changeUsername(userInfo)
        if (result) {
          // 修改用户名成功
          ElMessage({
            showClose: true,
            message: '保存成功🎉',
            type: 'success',
            duration: 1000
          })
          userStore.user.username = newUsername
          isEdit.value = false
        } else {
          // 修改用户名失败（用户名已存在）
          errorText.value = '用户名已存在'
          inputRef.value!.focus()
          return
        }
      } else {
        isEdit.value = false
      }
      errorText.value = ''
    }

    const isChangeAvatar = ref(false)

    const currentChooseAvatar = ref(-1)

    const useImageUrl = (imgPath: string) => {
      if (!imgPath) {
        return userStore.user.avatar
      }
      return new URL(`../assets/${imgPath}`, import.meta.url).href
    }

    // ImageUrl 保存用户上传的图片路径
    const ImageUrl = ref('')
    let Imagefile: File
    // 处理图片上传逻辑
    const handleFileUpload = (event: Event) => {
      const target = event.target as HTMLInputElement
      const file = target.files![0]
      if (file && file.type.startsWith('image/')) {
        // 将用户上传的图片进行预览
        ImageUrl.value = URL.createObjectURL(file)
        currentChooseAvatar.value = -1
        Imagefile = file
      }
    }

    const submit = async () => {
      if (ImageUrl.value) {
        // 构建 formData 用于发送 http 请求
        const formData = new FormData()
        formData.append('file', Imagefile)
        formData.append('username', userStore.user.username)
        const result = await userStore.uploadAvatar(formData)
        if (result) {
          ElMessage({
            showClose: true,
            message: '保存成功🎉',
            type: 'success',
            duration: 1000
          })
          ImageUrl.value = ''
          emit('closeUserInfo')
        } else {
          ElMessage({
            showClose: true,
            message: '保存失败😮‍💨',
            type: 'error',
            duration: 1000
          })
        }
      } else if (currentChooseAvatar.value > -1) {
        let userInfo = {
          username: userStore.user.username,
          avatar: avatars[currentChooseAvatar.value]
        }
        const result = await userStore.changeAvatar(userInfo)
        if (result) {
          ElMessage({
            showClose: true,
            message: '保存成功🎉',
            type: 'success',
            duration: 1000
          })
          currentChooseAvatar.value = -1
          emit('closeUserInfo')
        } else {
          ElMessage({
            showClose: true,
            message: '保存失败😮‍💨',
            type: 'error',
            duration: 1000
          })
        }
      } else {
        emit('closeUserInfo')
      }
    }

    const handleLogout = async () => {
      await userStore.logout()
      ElMessage({
        showClose: true,
        message: '再见👋',
        duration: 1000
      })
      emit('closeUserInfo')
    }

    return { userStore, isEdit, inputRef, avatars, useImageUrl, errorText, isChangeAvatar, handleChangeUsername, currentChooseAvatar, ImageUrl, handleFileUpload, submit, handleLogout }
  }
})
</script>

<style lang="less" scoped>
.container {
  background-color: rgba(255, 255, 255, 0.80);
  box-shadow: 0px 0px 4px 0px rgba(0, 0, 0, 0.1);
  width: 150px;
  padding: 20px;
  position: fixed;
  top: 60px;
  right: 20px;
  z-index: 1;
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  display: flex;
  justify-content: center;

  &.active {
    width: 350px;
  }

  .left {
    margin-top: 20px;
    margin-right: 30px;

    .choose-avatar {

      .icon-dagou {
        position: absolute;
        color: #5b5b5b;
        font-size: 20px;
        cursor: pointer;
        top: 9px;
        left: 16px;
      }

      .images {
        display: flex;
        justify-content: space-between;
        flex-wrap: wrap;
        margin-bottom: 7px;

        .image {
          margin-top: 7px;

          &.active {
            outline: 1px solid rgba(59, 115, 240, 1);
          }

          img {
            height: 50px;
            cursor: pointer;
          }
        }

        .up-loader {
          input[type="file"] {
            display: none;
          }

          /* 定义上传按钮的样式 */
          .custom-file-upload {
            width: 50px;
            height: 50px;
            margin-top: 7px;
            border: 1px dashed #949494;
            box-sizing: border-box;
            cursor: pointer;
            display: flex;
            justify-content: center;
            align-items: center;

            &:hover {
              border: 1px dashed rgba(59, 115, 240, 1);
            }

            .icon-tianjia {
              font-size: 25px;
              color: #949494;
            }
          }
        }
      }
    }
  }

  .right {
    margin-top: 20px;

    .header {
      width: 100px;
      height: 100px;
      border-radius: 50%;
      cursor: pointer;
      box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.1);
      overflow: hidden;
      border: 3px solid white;
      margin: auto;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .iconfont {
        position: absolute;
        top: 14px;
        right: 16px;
        color: #5b5b5b;
        cursor: pointer;
      }
    }

    .main {
      margin-top: 10px;
      text-align: center;

      input {
        width: 100%;
        text-align: center;
        box-sizing: border-box;
        font-size: 16px;

        &:focus {
          border: 1px dashed #949494;
        }
      }

      .username {
        font-size: 16px;
      }

      .error {
        height: 30px;
        line-height: 24px;
        font-size: 12px;
        color: #f55151;
      }

      .iconfont {
        margin-left: 2px;
        color: #949494;
        cursor: pointer;
      }
    }

    .footer {
      text-align: center;
    }
  }
}
</style>
